#include "ys_form_patient_detail.h"
#include "ui_ys_form_patient_detail.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QSqlError>
#include <windows.h>
#include <QDir>

extern int MAX_SQL_LENGTH ;

ys_form_patient_detail::ys_form_patient_detail(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ys_form_patient_detail)
{
    ui->setupUi(this);

    initial_finished = false;
    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/form_patient_detail").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    md_list_patient = new QSqlQueryModel();
    md_patient_detail = new QSqlQueryModel();
    md_rec_hist = new QSqlQueryModel();

    ui->de_reg_0->setDate(QDate::currentDate());
    ui->de_reg_1->setDate(QDate::currentDate());

    dlg_get_date = new pub_pop_get_date();
    dlgDelay = new Pub_pop_delay();

    //检查用户是否拥有 完整数据权限
    sq = "select name from com_privileges where role_dept = '全院数据查询'"
         " and name = '" + pub::usr_name + "'";
    qrm->exec(sq);

    if(qrm->next())
    {
        //有权限，提取全部科室列表
        sq = "select dept_name, dept_code from COM_DEPARTMENT where regdept_flag = '1' and valid_state = '1'";
        qrm->exec(sq);
        qDebug()<<"提取门诊科室列表 ： "<<sq;

        ui->cbb_dept->clear();
        ui->cbb_dept->addItem("全部");
        dept_code = pub::fillCombo(ui->cbb_dept, sq, 0, qro, false);
        dept_code = "全部^^" + dept_code ;

    }else{
        //无权限，本诊室

        ui->cbb_dept->clear();
        ui->cbb_dept->addItem(pub::dp_name);

        dept_code = pub::dp_name + "^" + pub::dp_code ;

        sq = "select name, lpad(code, 6, '0') from com_privileges where role_dept = '" + pub::dp_name + "'";

        ui->cbb_doct->clear();
        ui->cbb_doct->addItem("全部");
        doct_code = pub::fillCombo(ui->cbb_doct, sq, 0, false);
        doct_code = "全部^^" + doct_code ;

    }

    sq = "create temporary table if not exists tmp_doct_reg_count "
         "("
         "serial_number int,"   //序号
            "doct_dept VARCHAR(20) , "//
            "doct_name VARCHAR(12) , "//
            "patient_name VARCHAR(12) , "//
            "gender VARCHAR(2) ,"  //
            "age  VARCHAR(12), " //
            "phone VARCHAR(20),"    //
            "reg_date VARCHAR(20),"     //
            "clinic_code VARCHAR(20)"  //
            ") ";

    qDebug()<<"临时表："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note","未能成功建立临时表！");
        return;
    }

    display_id = "no_id";

    ui->tabWidget->setCurrentIndex(0);

    initial_finished = true;
}

ys_form_patient_detail::~ys_form_patient_detail()
{
    delete ui;
}

void ys_form_patient_detail::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/form_patient_detail", QVariant(this->geometry()));

    emit destroyW( "form_patient_detail" );

}

void ys_form_patient_detail::on_tb_reg_0_clicked()
{
    int t = ui->tb_reg_0->pos().y() + this->pos().y();
    int l = ui->tb_reg_0->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->de_reg_0->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();

    ui->de_reg_0->setDate(dlg_get_date->ret_date());

}

void ys_form_patient_detail::on_tb_reg_1_clicked()
{
    int t = ui->tb_reg_1->pos().y() + this->pos().y();
    int l = ui->tb_reg_1->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->de_reg_1->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();
    ui->de_reg_1->setDate(dlg_get_date->ret_date());
}

void ys_form_patient_detail::on_cbb_dept_currentTextChanged(const QString &arg1)
{
    if(!initial_finished)
    {
        return;
    }

    sq = "select name, lpad(code, 6, '0') from com_privileges where role_dept = '" + arg1 + "'";

    qDebug()<<"提取诊室关联的医生："<<sq;

    ui->cbb_doct->clear();
    ui->cbb_doct->addItem("全部");
    doct_code = pub::fillCombo(ui->cbb_doct, sq, 0, false);
    doct_code = "全部^^" + doct_code ;
}

void ys_form_patient_detail::on_pb_exit_clicked()
{
    close();
}

void ys_form_patient_detail::on_pb_list_patient_clicked()
{
    QString dateRangeR;

    if(ui->ckb_date->isChecked())
    {

        if(ui->de_reg_1->date() < ui->de_reg_0->date())
        {
            QMessageBox::information(this,"注意","指定的时间范围无效！");
            return;
        }

        QString begin = ui->de_reg_0->date().toString("yyyy-MM-dd");
        QString end = ui->de_reg_1->date().toString("yyyy-MM-dd");

        dateRangeR = " trunc(reg_date) >= to_date('" + begin + "','yyyy-mm-dd') ";
        dateRangeR += " and trunc(reg_date) <= to_date('" + end + "','yyyy-mm-dd') ";

    }
    else
    {
        dateRangeR = " 1 = 1 ";
    }

    QString tmp_dept, tmp_doct, tmp_patient, tmp_phone;
    int pos;

    if(ui->cbb_dept->currentText() == "全部" )
    {
        tmp_dept = "";
    }else
    {
        pos = pub::searchStr(dept_code, "^", ui->cbb_dept->currentText());
        QString dept = pub::getStr(dept_code, "^", pos + 1);
        tmp_dept = " and (see_dpcd = '" + dept + "' or dept_code = '" + dept + "' ) ";
    }

    if(ui->cbb_doct->currentText() == "全部" || ui->cbb_doct->currentText().isEmpty() )
    {
        tmp_doct = "";
    }
    else
    {
        pos = pub::searchStr(doct_code, "^", ui->cbb_doct->currentText());
        QString doct = pub::getStr(doct_code, "^", pos + 1);
        tmp_doct = " and see_docd = '" + doct + "' ";
    }

    tmp_patient = "";
    if(!ui->le_patient_name->text().trimmed().isEmpty())
    {
        if(ui->ckb_name_fuzzy->isChecked())
        {
            tmp_patient += " and name like '%" + ui->le_patient_name->text().trimmed() + "%' ";
        }
        else
        {
            tmp_patient += " and name = '" + ui->le_patient_name->text().trimmed() + "' ";
        }
    }

    if(!ui->le_card_no->text().trimmed().isEmpty())
    {
        tmp_patient += " and card_no = '" + pub::add0(ui->le_card_no->text().trimmed(), 10) + "' ";
    }

    if(!ui->le_clinic_code->text().trimmed().isEmpty())
    {
        tmp_patient += " and clinic_code = '" + ui->le_clinic_code->text().trimmed() + "' ";
    }


    if(!ui->le_iden_no->text().trimmed().isEmpty())
    {
        tmp_patient += " and idenno = '" + ui->le_iden_no->text().trimmed() + "' ";
    }

    if(!ui->le_rela_phone->text().trimmed().isEmpty())
    {
        tmp_phone += " and rela_phone = '" + ui->le_rela_phone->text().trimmed() + "' ";
    }

    if(ui->ckb_groupty_card_no->isChecked())
    {
        sq = "SELECT NAME 姓名, max(CASE WHEN SEX_CODE = 'F' THEN '女' ELSE '男' END ) 性别, " //0-1
             " max(round((reg_date - BIRTHDAY) / 365.25, 1)) 年龄, max(rela_phone ) 联系电话," //2-3
             " card_no 病志号, max( see_date ) 接诊时间, max(clinic_code),max( idenno)," //4-7
             " '' 费别 ,max(reg_date)" //8-9 max(CASE WHEN pact_code = '1' THEN '现金' ELSE '医保' END）
             " from fin_opr_register"
             " where %1 "
             " group by card_no,name ";
        sq = sq.arg(dateRangeR + tmp_dept + tmp_doct + tmp_patient + tmp_phone);

        if(ui->rb_reg_order->isChecked())
        {
            sq += " order by max(reg_date )";
        }
        else
        {
            sq += " order by max(see_date )";
        }
    }
    else
    {
        sq = "SELECT NAME 姓名, CASE WHEN SEX_CODE = 'F' THEN '女' ELSE '男' END 性别, " //0-1
             "round((reg_date - BIRTHDAY) / 365.25, 1) 年龄, rela_phone 联系电话, " //2-3
             "card_no 病志号, see_date 接诊时间,clinic_code, idenno," //4-7
             "CASE WHEN pact_code = '1' THEN '现金' ELSE '医保' END 费别,reg_date"//8-9
             " from fin_opr_register where ";
        sq += dateRangeR + tmp_dept + tmp_doct + tmp_patient + tmp_phone;
        sq += " and cancel_opcd is null and rownum < 9999 ";
        if(ui->rb_reg_order->isChecked())
        {
            sq += " order by reg_date ";
        }
        else
        {
            sq += " order by see_date ";
        }
    }

    qDebug()<<"抽取指定门诊患者列表："<<sq;

    dlgDelay->setText("提取指定时间的患者列表。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    md_list_patient->setQuery(sq, pub::db_o);
    int w = ui->tv_list_patient->width();
    ui->tv_list_patient->setModel(md_list_patient);
    pub::setColumnWidth(ui->tv_list_patient, "0.15^0.1^0.1^0^0.2^0.25^0^0^0.1^0",w);

    if(md_list_patient->rowCount() < 1)
    {
        QMessageBox::information(this,"注意","按指定的条件范围未能查询到数据！");
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return;
    }

    qro->exec(sq);
    qrm->exec("delete from tmp_doct_reg_count");
    int count = 0;
    QString dept = ui->cbb_dept->currentText();
    QString doct = ui->cbb_doct->currentText();
    if(doct.isEmpty())
    {
        doct = "全部";
    }

    time_elapse.restart();
    qDebug()<<"elapsed : "<<QString::number(time_elapse.elapsed());

    QString base_sql = "insert into tmp_doct_reg_count ("
                       "serial_number,"
                          "doct_dept, "//
                          "doct_name, "//
                          "patient_name, "//
                          "gender,"  //
                          "age, " //
                          "phone ,"    //
                          "reg_date,"     //
                          "clinic_code"  //
                          ") values ";
    QString val_sql;
    //int val_count = 50;
    //int cycle_count = 0;

    while(true)
    {
        count ++ ;

        sq = " (";
        sq += QString::number(count) + ",";
        sq += "'" + dept + "', ";
        sq += "'" + doct + "', ";
        sq += "'" + qro->value("姓名").toString() + "',";
        sq += "'" + qro->value("性别").toString() + "',";
        double ag = qro->value("年龄").toDouble();
        sq += "'" + QString::asprintf("%.1f", ag) + "',";
        sq += "'" + qro->value("联系电话").toString() + "',";
        sq += "'" + qro->value("接诊时间").toDate().toString("yyyy-MM-dd") + "',";
        sq += "'" + qro->value(6).toString() + "'";
        sq += ") ";

        val_sql.append(sq);

        if(!qro->next())
        {
            if(!qrm->exec( base_sql + val_sql ))
            {
                QMessageBox::warning(this, "注意", "插入临时数据发生错误！\n" + qrm->lastError().text());
                qDebug()<<"insert into tmp : "<<sq;
            }
            break;
        }
        //cycle_count ++ ;
        //if(cycle_count < val_count)
        if(val_sql.length() < MAX_SQL_LENGTH)
        {
            val_sql.append(" , ");
        }
        else
        {
            //cycle_count = 0;

            if(!qrm->exec( base_sql + val_sql ))
            {
                QMessageBox::warning(this, "注意", "插入临时数据发生错误！\n" + qrm->lastError().text());
                qDebug()<<"insert into tmp : "<<sq;
                break;
            }
            val_sql.clear();
        }
    }

    qDebug()<<"elapsed : "<<QString::number(time_elapse.elapsed());
    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

    ui->pt_after->clear();
    ui->pt_before->clear();

}

void ys_form_patient_detail::on_tv_list_patient_doubleClicked(const QModelIndex &index)
{
    on_tv_list_patient_clicked(index);
}

void ys_form_patient_detail::on_tv_list_patient_clicked(const QModelIndex &index)
{

    qDebug()<<"on_tv_list_patient_clicked\n";
    QString card_no = index.siblingAtColumn(4).data().toString();
    QString iden_no = index.siblingAtColumn(7).data().toString();
    QString phone = index.siblingAtColumn(3).data().toString();
    QString name = index.siblingAtColumn(0).data().toString();
    QString clinic_code = index.siblingAtColumn(6).data().toString();

    ui->le_card_no->setText(card_no);
    ui->le_clinic_code->setText(clinic_code);
    ui->le_iden_no->setText(iden_no);
    ui->le_rela_phone->setText(phone);
    ui->le_patient_name->setText(name);

    if(ui->tabWidget->currentIndex() == 0)
    {
        //患者诊疗记录
        if(display_id == iden_no + card_no)
        {
            //已经在展示指定的信息
            return;
        }

        display_id = iden_no + card_no; //保存新的当前id

        dlgDelay->setText("提取指定患者的历史就诊记录。。。");
        dlgDelay->setModal(true);
        dlgDelay->setNeedClose(false);
        dlgDelay->show();
        qApp->processEvents();


        if(card_no.isEmpty())
        {
            return;
        }
        qro->exec("delete from med_history");

        time_elapse.restart();

        //提取处方数据
        sq = "insert into med_history (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, clinic_code,diag)  ";
        sq += " select OPER_DATE,ITEM_NAME,SPECS,QTY,status,DOCT_NAME, clinic_code, "
              " CASE WHEN clinicotherdiag2_name IS NOT NULL THEN"
              " CONCAT ( CONCAT ((CASE WHEN clinicotherdiag1_name IS NOT NULL THEN CONCAT ("
              " CONCAT (clinicdiag_name, '，'),clinicotherdiag1_name)ELSE clinicdiag_name"
              " END),'，'),clinicotherdiag2_name) ELSE ( CASE WHEN clinicotherdiag1_name IS NOT NULL "
              " THEN CONCAT ( CONCAT (clinicdiag_name, '，'), clinicotherdiag1_name)ELSE clinicdiag_name END ) END 诊断 ";
        sq += " from met_ord_recipedetail where card_no='" + card_no + "' ";//order by sort_id";

        qDebug()<<"提取处方数据\n";

        if(!qro->exec(sq))
        {
            QMessageBox::warning(this, "注意", "提取处方历史数据发生错误！");
            qDebug()<<sq;
        }

        qDebug()<<""<<QString::number(time_elapse.elapsed());

        //提取挂号数据
        sq = "insert into med_history (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, clinic_code,diag)  ";
        sq += " select OPER_DATE,CONCAT( CONCAT(REGLEVL_NAME,' : ' ),DEPT_NAME) ,'-',1,TRANS_TYPE + 1 ,'-', clinic_code, '挂号'";
        sq += " from FIN_OPR_REGISTER where card_no='" + card_no + "' ";//order by sort_id";

        if(!qro->exec(sq))
        {
            QMessageBox::warning(this, "注意", "提取挂号历史数据发生错误！");
            qDebug()<<sq;
        }

        qDebug()<<""<<QString::number(time_elapse.elapsed());

        //提取回访数据
        sq = "select call_date, conclusion, memo from ys_bz_e_call where card_no = '" + card_no + "'";
        qrm->exec(sq);
        while(qrm->next())
        {
            sq = "insert into med_history (fee_ocur_time ,hilist_name, diag ) values ( ";
            sq += "to_date('" + qrm->value(0).toDate().toString("yyyy-MM-dd") + "','yyyy-mm-dd'),";
            sq += "'随访',";
            sq += "'" + qrm->value(1).toString() + "'";
            sq += ")";

            if(!qro->exec(sq))
            {
                QMessageBox::warning(this, "注意", "提取患者随访数据发生错误！");
                qDebug()<<sq;
            }
        }

        qDebug()<<""<<QString::number(time_elapse.elapsed());


        //显示完整诊疗记录
        sq = "select to_char(fee_ocur_time,'yyyy-mm-dd') 时间, diag 诊断 ,hilist_name 项目名称,"//0-2
             " spec 规格, cnt 数量, doct_name 医生, "//3-5
             "  case when setl_flag = '0' then '未付' else "
             " (case when setl_flag = '3' then '作废' else "
             " (case when setl_flag = '4' then '撤销' else '正常' end ) end ) end  标志 ," //6
             "  clinic_code "//7
             "from med_history order by fee_ocur_time ";


        md_patient_detail->setQuery(sq, pub::db_o);
        ui->tv_patient_detail->setModel(md_patient_detail);
        pub::setColumnWidth(ui->tv_patient_detail, "0.15^0.15^0.2^0.1^0.05^0.1^0.1", ui->tv_patient_detail->width(), 8);

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

    }
    else if(ui->tabWidget->currentIndex() == 1)
    {
        //病历修改记录
        sq = "select oper_time 时间点, fld_name 字段名称, fld_old 修改前, fld_new 修改后"
             " from ys_bz_e_rec_hist"
             " where clinic_code = '%1'"
             " order by oper_time";
        sq = sq.arg(clinic_code);

        qDebug()<<"病历修改记录:"<<sq<<"\n";
        md_rec_hist->setQuery(sq, pub::db_m);
        ui->tv_rec_hist->setModel(md_rec_hist);
        int w = ui->tv_rec_hist->width();
        pub::setColumnWidth(ui->tv_rec_hist, "0.2^0.2^0.23^0.23", w);

    }
    else if(ui->tabWidget->currentIndex() == 2)
    {

        qDebug()<<"显示详细病志：\n";

        ui->le_code->clear();
        ui->tb_rec_preview->clear();

        QString preview;
        QFile f(":/mzbl.html");

        if(f.open(QFile::ReadOnly))
        {
            preview = QString::fromUtf8(f.readAll());
            f.close();
        }
        else
        {
            QMessageBox::information(this, "note", "cann't open mzbl.html !");
            return;
        }

        qro->exec("select * from fin_opr_register where clinic_code = '" + clinic_code + "'");
        qro->next();
        QString dt = qro->value("reg_date").toDate().toString("yyyy-MM-dd");
        QString dpnm = qro->value("dept_name").toString();
        QString doct_code = qro->value("doct_code").toString();
        QString doct_name = qro->value("doct_name").toString();
        QString see_code = qro->value("see_docd").toString();

        if(doct_code != see_code)
        {
            doct_code = see_code;
            sq = "select empl_name from com_employee where empl_code = '" + doct_code + "' limit 1";
            qrm->exec(sq);

            qrm->next();
            doct_name = qrm->value(0).toString();
        }

        QString gend = qro->value("sex_code").toString();
        if(gend == "F")
        {
            gend = "女";
        }
        else
        {
            gend = "男";
        }

        preview.replace("--姓名--", qro->value("name").toString());
        preview.replace("--性别--", gend);
        QDate rg = qro->value("reg_date").toDate();
        QDate bd = qro->value("birthday").toDate();

        int days = bd.daysTo(rg);
        preview.replace("--年龄--", QString::asprintf("%.1f", double(days)/365.25));
        preview.replace("--病志号--", card_no);
        preview.replace("--诊室--", dpnm);

        preview.replace("--就诊时间--", rg.toString("yyyy-MM-dd"));
        preview.replace("--主治医生--", doct_name);

        preview.replace("<strong> 医保卡号：</strong> --医保卡号--", "");

        sq="select xmmc, xmjg from ys_bz_e_lib where clinic_code = '" + clinic_code + "'";
        qrm->exec(sq);
        QString tmp_str = "";
        while(qrm->next())
        {
            if(qrm->value(1).toString().isEmpty())
            {
                //化验无结果
                continue;
            }
            tmp_str += qrm->value(0).toString();
            tmp_str += " : ";
            tmp_str += qrm->value(1).toString();
            tmp_str += " ; ";
        }

        if(tmp_str.isEmpty())
        {
            preview.replace("<strong> 辅助检查：</strong> <br> --辅助检查-- <br>", "");
        }
        else
        {
            preview.replace("--辅助检查--", tmp_str);
        }


        sq="select * from ys_bz_e_rec where clinic_code = '" + clinic_code + "'";

        qrm->exec(sq);
        qrm->next();

        preview.replace("--患者主诉--", qrm->value("hzzs").toString());
        preview.replace("--现病史--", qrm->value("xbs").toString());
        preview.replace("--既往史--", qrm->value("jws").toString());
        preview.replace("--过敏史--", qrm->value("gms").toString());
        preview.replace("--个人史--", qrm->value("person_hist").toString());
        preview.replace("--诊疗计划--", qrm->value("medical_plan").toString());
        preview.replace("--医嘱--", qrm->value("yz").toString());
        preview.replace("--家族史--", qrm->value("family_hist").toString());
        preview.replace("--体格检查--", qrm->value("tgjc").toString());

        if(gend == "女")
        {
            preview.replace("--月经史--", qrm->value("menstr_hist").toString());
        }
        else
        {
            preview.replace("<strong> 月经史：</strong> <br> --月经史-- <br>","");
        }

        QString zd = qrm->value("zd1").toString() + " / " + qrm->value("zd1c").toString();
        if(!qrm->value("zd2").toString().isEmpty()){
            zd.append(", " + qrm->value("zd2").toString() + " / " + qrm->value("zd2c").toString());
        }
        if(!qrm->value("zd3").toString().isEmpty()){
            zd.append(", " + qrm->value("zd3").toString() + " / " + qrm->value("zd3c").toString());
        }

        preview.replace("--ICD诊断--", zd);
        preview.replace("<strong> ICPC诊断：</strong> <br> --ICPC诊断-- <br>", "");


        //☆‖·¨．◆ .§
        QString zyzd = qrm->value("zyzd1").toString()
                + "["
                + qrm->value("zyzh1").toString()
                + "] / "
                + qrm->value("zyzd1c").toString()
                + "["
                + qrm->value("zyzh1c").toString()
                + "]";

        if(!qrm->value("zyzd2").toString().isEmpty())
        {
            zyzd.append(", "
                      + qrm->value("zyzd2").toString()
                      + "["
                      + qrm->value("zyzh2").toString()
                      + "] / "
                      + qrm->value("zyzd2c").toString()
                      + "["
                      + qrm->value("zyzh2c").toString()
                      + "]");
        }
        if(!qrm->value("zyzd3").toString().isEmpty())
        {
            zyzd.append(", "
                      + qrm->value("zyzd3").toString()
                      + "["
                      + qrm->value("zyzh3").toString()
                      + "] / "
                      + qrm->value("zyzd3c").toString()
                      + "["
                      + qrm->value("zyzh3c").toString()
                      + "]");
        }

        preview.replace("--就诊原因--", qrm->value("jzyy").toString() + " / " + qrm->value("jzyyc").toString());

        if(qrm->value("zyzd1").toString().isEmpty())
        {
            preview.replace("<strong> 中医类证鉴别：</strong> <br> --中医类证鉴别-- <br>", "");
            preview.replace("<strong> 治则：</strong> <br> --治则-- <br>", "");
            preview.replace("<strong> 中医查体：</strong> <br> --中医查体-- <br>", "");
            preview.replace("<strong> 中医诊断：</strong> <br> --中医诊断-- <br>", "");
            preview.replace("<strong> 辨证依据</strong> <br> --辨证依据-- <br>", "");
        }
        else
        {
            preview.replace("--中医类证鉴别--", qrm->value("similar_syndrom").toString());
            preview.replace("--治则--", qrm->value("treat_tr").toString());
            preview.replace("--中医查体--", qrm->value("tgjc_tr").toString());
            preview.replace("--中医诊断--", zyzd);
            preview.replace("--辨证依据--", qrm->value("zybz").toString());
        }

        ui->tb_rec_preview->setHtml(preview);
    }

}

void ys_form_patient_detail::on_pb_export_clicked()
{

    dlgDelay->setText("正在导出数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    sq = "select reg.serial_number, reg.doct_dept, reg.doct_name, reg.patient_name,"
         "reg.gender, reg.age, reg.phone, reg.reg_date ,"
         " rec.zd1, rec.zd2, rec.zd3 "
         " from tmp_doct_reg_count reg "
         " left join ys_bz_e_rec rec on reg.clinic_code = rec.clinic_code ";     //
    sq += " order by serial_number ";
    qDebug()<<"提取接诊量 ："<<sq;
    qrm->exec(sq);

    QJsonDocument d;
    QJsonArray jsa_val;    //数值
    QJsonObject jot;  // 临时json
    int row = 3;
    int rowCount = 0;

    while(qrm->next())
    {
        row ++;
        rowCount ++ ;

        jot.insert("val", qrm->value("serial_number").toString());
        jot.insert("row", row);
        jot.insert("col", 1);
        jsa_val << jot;

        jot.insert("val", qrm->value("doct_dept").toString());
        jot.insert("row", row);
        jot.insert("col", 2);
        jsa_val << jot;

        jot.insert("val", qrm->value("doct_name").toString());
        jot.insert("row", row);
        jot.insert("col", 3);
        jsa_val << jot;

        jot.insert("val", qrm->value("patient_name").toString());
        jot.insert("row", row);
        jot.insert("col", 4);
        jsa_val << jot;

        jot.insert("val", qrm->value("gender").toString());
        jot.insert("row", row);
        jot.insert("col", 5);
        jsa_val << jot;

        jot.insert("val", qrm->value("age").toString());
        jot.insert("row", row);
        jot.insert("col", 6);
        jsa_val << jot;

        jot.insert("val", qrm->value("phone").toString());
        jot.insert("row", row);
        jot.insert("col", 7);
        jsa_val << jot;

        jot.insert("val", qrm->value("reg_date").toString());
        jot.insert("row", row);
        jot.insert("col", 8);
        jsa_val << jot;

        QString diag = qrm->value("zd1").toString();

        if(!qrm->value("zd2").toString().isEmpty())
        {
            diag += qrm->value("zd2").toString().isEmpty();
        }

        if(!qrm->value("zd3").toString().isEmpty())
        {
            diag += qrm->value("zd3").toString().isEmpty();
        }

        jot.insert("val", diag);
        jot.insert("row", row);
        jot.insert("col", 9);
        jsa_val << jot;

    }

    QString date_range = "日期范围：";
    date_range += ui->de_reg_0->date().toString("yyyy/MM/dd");
    date_range += " - ";
    date_range += ui->de_reg_1->date().toString("yyyy/MM/dd");
    jot.insert("val", date_range);
    jot.insert("row", 2);
    jot.insert("col", 1);
    jsa_val << jot;

    QString dept = "诊室：";
    dept += ui->cbb_dept->currentText();
    jot.insert("val", dept);
    jot.insert("row", 2);
    jot.insert("col", 8);
    jsa_val << jot;

    QString doct = "医师：";
    if(ui->cbb_doct->currentText().isEmpty())
    {
        doct += "全部";
    }
    else
    {
        doct += ui->cbb_doct->currentText();
    }


    jot.insert("val", doct);
    jot.insert("row", 2);
    jot.insert("col", 9);
    jsa_val << jot;


    QJsonArray jsa_rng;    //表格区域
    jot = d.object();
    QString rg = QString("A3:I%1").arg(QString::number( rowCount + 3 ));
    jot.insert("range", rg);
    jsa_rng << jot;

    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/menzhengongzuobaobiao.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("grid_range", jsa_rng);
    jo.insert("process_mode", "s"); //只保存，不打印

    pub::printOutExcel(jo);

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

//    QFile fl(source_file);
//    if(!fl.exists())
//    {
//        QMessageBox::information(NULL, "注意", "生成报表文件失败！");
//        return;
//    }

//    if(fl.copy(fileName))
//    {
//        QString path = QDir::currentPath();
//        QMessageBox::information(NULL, "注意", "报表文件已生成，路径为 " + path.mid(0, 2) + fileName + "。");
//    }
//    else
//    {
//        QMessageBox::information(NULL, "注意", "复制报表文件失败！");
//    }



}

void ys_form_patient_detail::on_pb_clear_clicked()
{
    ui->le_patient_name->clear();
    ui->le_card_no->clear();
    ui->le_clinic_code->clear();
    ui->le_iden_no->clear();
    ui->le_rela_phone->clear();
    ui->tv_patient_detail->setModel(NULL);
    display_id = "no_id";
    ui->ckb_name_fuzzy->setChecked(false);
    ui->ckb_groupty_card_no->setChecked(true);
}

void ys_form_patient_detail::on_tv_patient_detail_doubleClicked(const QModelIndex &index)
{
    QString sq, txt;
    QString diag = index.siblingAtColumn(1).data().toString();
    QString clinicCode = index.siblingAtColumn(7).data().toString();

    if(diag != "挂号")
    {
        //当前点击为非挂号记录
        return;
    }

    sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , 'l.xmmc', 'l.xmjg', 'p.lxdh' ,r.zd1,r.zd2,r.zd3"
       " from ys_bz_e_rec r "
       " where clinic_code = '" + clinicCode + "'";

    qrm->exec(sq);

    txt = "";

    if(qrm->next())
    {
        //txt.append("患者姓名：" + patient_name + " , 联系电话：" +rela_phone + "\n\r\n\r");
        //txt.append("病志号：" + card_no +  "     诊室名称：" + deptName + "\n\r");
        txt.append("主诉：" + qrm->value("hzzs").toString() + "\n\r");
        txt.append("现病史：" + qrm->value("xbs").toString() + "\n\r");
        txt.append("既往史：" + qrm->value("jws").toString() + "\n\r");
        txt.append("检查：" + qrm->value("tgjc").toString() + "\n\r");
        QString zd = qrm->value("zd1").toString();

        if(!qrm->value("zd2").toString().isEmpty()){
            zd.append(", " + qrm->value("zd2").toString());
        }
        if(!qrm->value("zd3").toString().isEmpty()){
            zd.append(", " + qrm->value("zd3").toString());
        }

        txt.append("医嘱：" + qrm->value("yz").toString() + "\n\r");

        QMessageBox::information(this,"病志信息", txt);
    }
    else
    {
        QMessageBox::information(this,"注意","找不到关联的诊断信息！");
    }

}

void ys_form_patient_detail::on_tv_rec_hist_doubleClicked(const QModelIndex &index)
{
    on_tv_rec_hist_clicked(index);
}

void ys_form_patient_detail::on_tv_rec_hist_clicked(const QModelIndex &index)
{
    ui->pt_before->setPlainText(index.siblingAtColumn(2).data().toString());
    ui->pt_after->setPlainText(index.siblingAtColumn(3).data().toString());
}

void ys_form_patient_detail::on_pb_rec_check_clicked()
{
    if(!ui->tv_list_patient->currentIndex().isValid())
    {
        QMessageBox::information(this,"注意","未选定有效挂号记录！");
        return;
    }

    QString clinic_code = ui->tv_list_patient->currentIndex()
            .siblingAtColumn(6).data().toString();

    QString sm3_screen = ui->le_code->text().trimmed();

    if(sm3_screen.isEmpty())
    {
        QMessageBox::information(this,"注意","请输入校验码！");
        ui->le_code->setFocus();
        return;
    }

    sq = " select tmstmp from ys_bz_e_rec_sm3 where clinic_code = '" + clinic_code + "'";
    sq += " and sm3_code = '" + sm3_screen + "'";
    qrm->exec(sq);

    if (!qrm->next())
    {
        QMessageBox::information(this,"注意","输入的校验码在数据库中找不到匹配记录！");
        ui->le_code->setFocus();
        return;
    }

    QString time_check = qrm->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString sm3_msg = "输入的校验码生成时间：" + time_check+ "\n";

    sq = " select sm3_code from ys_bz_e_rec_sm3 where clinic_code = '" + clinic_code + "'";
    sq+= " order by tmstmp desc";
    qrm->exec(sq);
    qrm->next();

    QString sm3_last = qrm->value(0).toString();

    if(sm3_last != sm3_screen)
    {
        sm3_msg += "此校验码非最终病志校验码。\n";
        //+ qrm->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss") + "\n";
    }

    QString prt_msg = "";

    sq = " select print_time from ys_bz_e_rec_print_rec where clinic_code = '" + clinic_code + "'";
    sq += " and sm3 = '" + sm3_screen + "'";
qDebug()<<sq;
    qrm->exec(sq);
    while (qrm->next())
    {
        prt_msg += qrm->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss") + "\n";
    }

    if(prt_msg.isEmpty())
    {
        prt_msg = "此校验码没有打印记录。";
    }
    else
    {
        prt_msg = "校验码关联病志打印时间记录：\n" + prt_msg;
    }

    QMessageBox::information(this,"注意", sm3_msg + prt_msg);

}

void ys_form_patient_detail::on_tabWidget_currentChanged(int index)
{

    if(index > 0)
    {
        ui->ckb_groupty_card_no->setChecked(false);
    }
}
